import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus';
import viteCompression from 'vite-plugin-compression';
import { buildConfig } from './src/utils/build';
import vueJsx from '@vitejs/plugin-vue-jsx'
import { viteMockServe } from 'vite-plugin-mock'

const pathResolve = (dir: string) => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'/@': pathResolve('./src/'),
	'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
};
const extensions:string[] = [".js", ".json", ".ts", ".vue", ".tsx"] // 使用路径别名时想要省略的后缀名
const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		plugins: [
			vue(), 
			vueJsx(), 
			vueSetupExtend(), 
			viteCompression(), 
			JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.cdn() : null,
			viteMockServe()
		],
		root: process.cwd(),
		resolve: { alias, extensions},
		base: '/',
		optimizeDeps: { 
			include: [
        		'public/vform/designer.umd.js', //此处路径必须跟main.js中import路径完全一致！
				'bpmn-js/lib/Modeler',
				'bpmn-js/lib/features/label-editing/LabelUtil.js',
				'element-plus/es/locale/lang/zh-cn', 
				'element-plus/es/locale/lang/en', 
				'element-plus/es/locale/lang/zh-tw',
				'monaco-editor/esm/vs/language/json/json.worker',
				'monaco-editor/esm/vs/language/css/css.worker',
				'monaco-editor/esm/vs/language/html/html.worker',
				'monaco-editor/esm/vs/language/typescript/ts.worker',
				'monaco-editor/esm/vs/editor/editor.worker'
			],	
		},
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT as unknown as number,
			open: JSON.parse(env.VITE_OPEN),
			hmr: true,
			proxy: {
				'/api': {
					target: 'http://localhost:8903',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, ''),
				},
			},
		},
		build: {
			outDir: 'dist',
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//)?.groups!.moduleName ?? 'vender';
						}
					},
				},
				...(JSON.parse(env.VITE_OPEN_CDN) ? { external: buildConfig.external } : {}),
			},
      // commonjsOptions: {
      //   include: /node_modules|lib/  //这里记得把lib目录加进来，否则生产打包会报错！！
      // }
		},
		css: { preprocessorOptions: { css: { charset: false } } },
		define: {
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});

export default viteConfig;
